package cn.hejiang.basic.controller;

import cn.hejiang.basic.util.AjaxResult;
import cn.hejiang.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController // 复合注解
@RequestMapping("/fastDfs")
public class FastDfsController {

    // 上传接口
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true, value = "file") MultipartFile file) {
        // 获取文件后缀
        try {
            String filename = file.getOriginalFilename();
            String substring = filename.substring(filename.lastIndexOf(".") + 1);
            return AjaxResult.me().setResultObj(FastDfsUtil.upload(file.getBytes(), substring));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，已滚出！");
        }
    }

    // 删除接口
    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true, value = "path") String path) {
        // 获取文件后缀
        try {
            String pathTmp = path.substring(1);
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastDfsUtil.delete(groupName, remotePath);
            return AjaxResult.me();

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("系统繁忙，已滚出！");
        }
    }
}
